<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架 [ 以下开发工具自动生成-版权勿删 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace addons\cloud_market\model;


/**
 * 标签管理模型文件
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 */
class CloudMarketLabel extends CloudMarketBaseModel
{

    // 字段自动类型转换
    protected $type = array();
    // 数据输出需要追加的属性
    protected $append = array();

    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }


    /**
     * 关联CloudMarketUser模型
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(CloudMarketUser::class, 'user_id', 'id');
    }


    public function getLabelIds($label_ids, $user_id, $type = 1)
    {
        $new_ids = [];
        foreach ($label_ids as $key => $value) {
            if (!$value) {
                continue;
            }
            if (intval($value) > 0) {
                $new_ids[] = intval($value);
            } else {
                $Label = new CloudMarketLabel();
                $label = $Label->where(['name' => $value])->findOrEmpty();
                if ($label->isEmpty()) {
//                    $label->name = $value;
//                    $label->user_id = $user_id;
//                    $label->type = $type;
                    $label->save([
                        'name' => $value,
                        'user_id' => $user_id,
                        'type' => $type,
                    ]);
                }
                $new_ids[] = $label->id;
            }
        }
        return $new_ids;
    }
}
